﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using DQYT.HTDZ.OracleDAL;
using System.Data;
using DQYT.HTDZ.Model;
namespace SkWeb.Handlers
{
    /// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public class Upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {

                string tmpId = context.Request["TmpID"].ToString();

                string virtualPath = "DesignSchemeTempalte/Tempalte/";

                int chunk = context.Request["chunk"] != null ? int.Parse(context.Request["chunk"]) : 0;
                int chunks = context.Request["chunks"] != null ? int.Parse(context.Request["chunks"]) : 0;
                string fileName = context.Request["name"] != null ? context.Request["name"] : string.Empty;

                HttpPostedFile fileUpload = context.Request.Files[0];
                var uploadPath = context.Server.MapPath("../" + virtualPath);

                using (var fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
                {
                    var buffer = new byte[fileUpload.InputStream.Length];
                    fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, buffer.Length);
                }

                //如果正确继续执行，错误则抛出异常
                context.Response.ContentType = "text/plain";
                context.Response.Write("{\"jsonrpc\" : \"2.0\", \"result\" : \"上传成功\", \"id\" : \"id\"}");

                if (chunk == 0)
                {
                    TB_Template_Menu_DAL tmpMenu = new TB_Template_Menu_DAL();

                    TB_Template_Menu_Model menuModel = new TB_Template_Menu_Model();
                    menuModel._parentId = Convert.ToInt32(tmpId);
                    menuModel.TMP_URL = "DesignSchemeTempalte/Tempalte/" + fileName; //relativePathAndName.Substring(0, relativePathAndName.LastIndexOf("\\") + 1) + fileName;
                    menuModel.TMP_MC = fileName;
                    menuModel.TMP_SX = 0;
                    menuModel.TMP_ZT = 1;
                    menuModel.TYP_CODE = 30;
                    tmpMenu.AddItem(menuModel);
                }



            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 102, \"message\":" + ex.Message + "\"}, \"id\" : \"id\"}");
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }

}